﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace XML的序列化与反序列化
{
    public sealed class XmlSerializerUnitity<T> where T:class,new ()
    {
        public static T XMLDeserialize(string filefullname) {
            try
            {
                using (FileStream fs = new FileStream(filefullname, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    Type t = typeof(T);
                    XmlSerializer xs = new XmlSerializer(t);
                    var result = (T)xs.Deserialize(fs);
                    return result;
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
        public static void XMLSerialize(T t, string filefullname) {
            try
            {
                using (MemoryStream ms=new MemoryStream ())
                {
                    XmlTextWriter xw = new XmlTextWriter(ms, Encoding.UTF8);
                    xw.Formatting = Formatting.Indented;
                    XmlSerializer xs = new XmlSerializer(t.GetType());
                    xs.Serialize(xw, t);
                    ms.Seek(0, SeekOrigin.Begin);
                    StreamReader sr = new StreamReader(ms);
                    string str = sr.ReadToEnd();
                    File.WriteAllText(filefullname,str);
                }
            }
            catch (Exception)
            {
                return;
            }
        }
    }
}
